package com.yonyou.cyxdms.basedata.service.service.sap;

import com.alibaba.fastjson.JSON;
import com.yonyou.cyxdms.basedata.service.entity.sap.DealerToSapPO;
import com.yonyou.cyxdms.basedata.service.repository.sap.DealerToSapMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;

@Service
@Slf4j
public class DealerToSapServiceImpl implements DealerToSapService {

    @Autowired
    DealerToSapMapper dealerToSapMapper;

    /**
     * @param request
     * @param response
     * @return 主键id
     */
    @Override
    public Long saveLog(String batchNo, String interfaceNo, Object request, Object response, Exception e){
        try {
            String key = interfaceNo;
            String requestBody = JSON.toJSONString(request);
            String responseBody = JSON.toJSONString(response);
            String createdBy = "-1";
            LocalDateTime createdAt = LocalDateTime.now();
            DealerToSapPO po = new DealerToSapPO();
            po.setRequestKey(key);
            po.setRequestBody(requestBody);
            po.setResponseBody(responseBody);
            if(e != null){
                po.setExceptionMessage(getStackTrace(e));
            }
            po.setBatchNo(batchNo);
            po.setRetryCount(0);
            po.setCreatedAt(createdAt);
            po.setUpdatedAt(createdAt);
            po.setCreatedBy(createdBy);
            po.setUpdatedBy(createdBy);
            dealerToSapMapper.insert(po);
            return po.getId();
        }catch (Exception e2){
            log.error("接口{}异常:{}",interfaceNo,getStackTrace(e2));
            return 0L;
        }

    }

    @Override
    public Long updateLog(Long id, Object response, Throwable e){
        Long errorLogId = 0L;
        if(errorLogId.equals(id)){
            return id;
        }
        DealerToSapPO po = dealerToSapMapper.selectById(id);
        LocalDateTime createdAt = LocalDateTime.now();
        String responseBody = JSON.toJSONString(response);
        po.setResponseBody(responseBody);
        if(e != null){
            po.setExceptionMessage(getStackTrace(e));
        }
        po.setUpdatedAt(createdAt);
        dealerToSapMapper.updateById(po);
        return id;
    }


    /**
     * 获取完整的异常信息
     *
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            throwable.printStackTrace(pw);
            return String.valueOf(sw);
        } finally {
            pw.close();
        }
    }

}
